"""
Form helpers.
"""
from django.forms import ValidationError
from django.forms.fields import EMPTY_VALUES, Field
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _

##########
# Fields #
##########

class NGPhoneNumberField(Field):
	"""
	A form field, which ensures that the number entered is a Nigerian phone number.

	The validated number is normalized, before being returned.
	"""

	default_error_messages = {
		'dialcode_error': _(u"Country prefix can't be followed by the digit '0'."),
		'number_invalid': _(u"Enter a valid phone number."),
	}

	def __init__(self, include_prefix=False, grouped=True, **kwargs):
		super(NGPhoneNumberField, self).__init__(**kwargs)
		self._include_prefix = include_prefix
		self._grouped = grouped

	def clean(self, value):
		from localflavor.ng.phone_numbers import clean_phone_number, DialCodeError, PhoneNumberInvalid
		value = super(NGPhoneNumberField, self).clean(value)
		if value in EMPTY_VALUES:
			return u''
		try:
			return clean_phone_number(smart_unicode(value), self._include_prefix, self._grouped)
		except DialCodeError:
			raise ValidationError(self.default_error_messages['dialcode_error'])
		except PhoneNumberInvalid:
			raise ValidationError(self.default_error_messages['number_invalid'])
